import { axiosInstance } from 'src/boot/axios'
import CommonConfig from 'src/assets/js/config'
import qs from 'qs'

const qsConfig = {
  arrayFormat: 'repeat',
  skipNulls: true,
  format: 'RFC3986'
}

const craft = CommonConfig.processUrl + '/v1'

/**
 * 列举产品
 * @param pageNum 页码
 * @param pageSize 每页条数
 * @param [searchBy] 搜索依据
 * @param [keyword] {string} 关键字
 * @returns {Promise<unknown>} promise
 */
function listProducts (pageNum, pageSize, { searchBy, keyword }) {
  const url = craft + '/products'

  let config = {
    params: {
      pageNum,
      pageSize,
      hasUsingCraftOnly: true,
      searchBy: searchBy || undefined,
      keyword: keyword || undefined
    }
  }

  return axiosInstance.get(url, config).then(resp => {
    return Promise.resolve(resp)
  })
}

/**
 * 列举产品的工序信息
 * @param ids 产品 ID 数组
 * @returns {Promise<*>} promise
 */
function listProductsProcesses (ids) {
  const url = craft + '/process_info_by_product'

  let config = {
    params: {
      productIds: ids
    },
    paramsSerializer: function (params) {
      return qs.stringify(params, qsConfig)
    }
  }

  return axiosInstance.get(url, config).then(resp => {
    return Promise.resolve(resp)
  })
}
/**
 * 编辑工艺信息
 */
function editProcessInfo (params) {
  const url = craft + '/process_info'

  return axiosInstance.put(url, params).then(resp => {
    return Promise.resolve(resp)
  })
}
/**
 * 修改工时定额
 */
function editProcessTime (params) {
  const url = craft + '/process_info/working_hours_quota'

  return axiosInstance.put(url, params).then(resp => {
    return Promise.resolve(resp)
  })
}
function getProcessRecord (params) {
  const url = craft + '/process_operation_record'

  return axiosInstance.get(url, { params }).then(res => {
    return Promise.resolve(res.data)
  })
}

function exportProcessRecord (params) {
  const url = craft + '/process_operation_record/excel:export'

  return axiosInstance.get(url, { params }).then(res => {
    return Promise.resolve(res)
  })
}

// 下载excel
export function downloadHourNormExcel (query) {
  const url = `${craft}/process_operation/excel:export`

  return axiosInstance.post(url, query).then(resp => {
    return Promise.resolve(resp)
  })
}

export default {
  listProducts,
  listProductsProcesses,
  editProcessInfo,
  editProcessTime,
  getProcessRecord,
  exportProcessRecord
}
